﻿using System;
using System.IO;
using System.Windows.Controls;


namespace Common.Untils
{
    /// <summary>
    ///     日记文件，用来记录出错的数据内容
    /// </summary>
    public static class Log {
        const int MaxSize = 1024 * 1024 * 5;
        /// <summary>
        ///     写日记文本，追加的模式
        /// </summary>
        public static void WriteLog(string objectname, string strmessage) {
            lock(new object()) {
                if(string.IsNullOrEmpty(strmessage)) return;
                string fn = string.Format("{0}\\Log\\{1:yyyyMMdd}\\{1:yyyy-MM-dd}.log", Environment.CurrentDirectory, DateTime.Now);
                string contents = string.Format("<{0}> {1}", objectname, strmessage);
                CreateLogFile(fn);

                FileInfo fileinfo = new FileInfo(fn);
                //当log文件超过2M大小时候，重新分配新的LOG文件
                if(fileinfo.Length > MaxSize) {
                    string destFileName = string.Format("{0}\\Log\\{1:yyyyMMdd}\\{1:yyyyMMddHHmmss}.log", Environment.CurrentDirectory, DateTime.Now);
                    File.Move(fn, destFileName);
                    CreateLogFile(fn);
                }

                try {
                    using(StreamWriter sw = File.AppendText(fn)) {
                        sw.WriteLine(DateTime.Now.ToString("HH:mm:ss.fff"));
                        sw.WriteLine(contents);
                        //  sw.WriteLine("------------------------------------------------------------------------");
                        sw.Close();
                    }
                }
                catch(Exception ex) {
                    Console.WriteLine(ex.Message);
                }
            }
        }

        /// <summary>
        /// 多参数日记文件
        /// </summary>
        /// <param name="objectname">日记来源</param>
        /// <param name="message">参数内容</param>
        public static void WriteLog(string objectname, params string[] message) {
            lock(new object()) {
                foreach(string t in message) {
                    WriteLog(objectname, t);
                }
            }
        }

        private static void CreateLogFile(string fn) {
            DirectoryInfo dellogpath = new DirectoryInfo(Environment.CurrentDirectory + "\\Log\\" + DateTime.Now.ToString("yyyyMMdd"));
            if(!Directory.Exists(dellogpath.ToString())) Directory.CreateDirectory(dellogpath.ToString());

            if(File.Exists(fn)) return;
            using(File.Create(fn)) {
            }
        }

        /// <summary>
        /// </summary>
        /// <param name="rtb"></param>
        /// <param name="strmessage"></param>
        //public static void WriteLog(ref RichTextBox rtb, string strmessage) {
        //    lock(new object()) {
        //        string contents = string.Format("<{0}> {1}\r", DateTime.Now, strmessage);
        //        rtb.AppendText(contents);
        //        rtb.ScrollToCaret();
        //        WriteLog("检定流程", strmessage);
        //    }
        //}

        /// 专用于记录异常信息
        /// <summary>
        ///     专用于记录异常信息
        /// </summary>
        /// <param name="objectName">标题</param>
        /// <param name="ex">异常信息</param>
        public static void WriteLog(string objectName, Exception ex) {
            string strMessage = string.Format("Message：{0}\r\nSource：{1}\r\nTargetSite：{2}\r\nStackTrace：\r\n{3}", ex.Message, ex.Source, ex.TargetSite, ex.StackTrace);
            WriteLog(objectName, strMessage);
        }

        /// <summary>
        ///     写日记文本，追加的模式
        /// </summary>
        public static void WriteLog(string fn, string objectname, string strmessage) {
            lock(new object()) {
                string contents = string.Format("{0}-<{1}>{2}", DateTime.Now, objectname, strmessage);
                try {
                    CreateLogFile(fn);
                    using(StreamWriter sw = File.AppendText(fn)) {
                        sw.WriteLine(contents);
                        sw.Close();
                    }
                }
                catch(Exception ex) {
                    WriteLog("WriteLog", ex);
                }
            }
        }

        /// <summary>
        ///     写报文记录
        /// </summary>
        /// <param name="message">报文记录</param>
        /// <param name="writeLevel">等级，默认-1，分别支持0,1,2,数字越高，等级越小
        /// <para>0=增加-------分隔符号</para>
        /// <para>1=增加———————分隔符号</para>
        /// <para>2=增加=========分隔符号</para>
        /// <para>-1表示无符号间隔</para>
        /// </param>
        public static void WriteLogSendEMByte(string message, int writeLevel = -1) {
            lock(new object()) {
                string fn = string.Format("{0}\\Log\\{1:yyyyMMdd}\\{1:yyyy-MM-dd}-EM.log", Environment.CurrentDirectory, DateTime.Now);
                CreateLogFile(fn);
                string path = string.Format("{0}\\Log\\{1:yyyyMMdd}", Environment.CurrentDirectory, DateTime.Now);
                DirectoryInfo root = new DirectoryInfo(path);
                FileInfo[] files = root.GetFiles();
                foreach(FileInfo item in files) {
                    if(!item.Name.Contains("EM.log")) continue;
                    using(StreamWriter sw = File.AppendText(item.FullName)) {
                        switch(writeLevel) {
                            case 0:
                                sw.WriteLine("-------------------------------------------------");
                                break;
                            case 1:
                                sw.WriteLine("——————————————————————————————————————————————————");
                                break;
                            case 2:
                                sw.WriteLine("==================================================");
                                break;
                        }
                        sw.WriteLine(message);
                        switch(writeLevel) {
                            case 0:
                                sw.WriteLine("-------------------------------------------------");
                                break;
                            case 1:
                                sw.WriteLine("——————————————————————————————————————————————————");
                                break;
                            case 2:
                                sw.WriteLine("==================================================");
                                break;
                        }
                        sw.Close();
                    }
                }
                //var fileinfo = new FileInfo(fn);
                ////当log文件超过2M大小时候，重新分配新的LOG文件
                //if(fileinfo.Length > MaxSize) {
                //    string destFileName = string.Format("{0}\\Log\\{1:yyyyMMdd}\\{1:yyyyMMddHHmmss}-EM.log", Environment.CurrentDirectory, DateTime.Now);
                //    File.Move(fn, destFileName);
                //    CreateLogFile(fn);
                //}
                //using(StreamWriter sw = File.AppendText(fn)) {
                //    sw.WriteLine(message);
                //    sw.Close();
                //}
            }
        }

        /// <summary>
        ///     写报文记录
        /// </summary>
        /// <param name="message">报文记录</param>
        /// <param name="writeLevel">等级，默认-1，分别支持0,1,2,数字越高，等级越小
        /// <para>0=增加-------分隔符号</para>
        /// <para>1=增加———————分隔符号</para>
        /// <para>2=增加=========分隔符号</para>
        /// <para>-1表示无符号间隔</para>
        /// </param>
        public static void WriteRfidLogSendEMByte(string message) {
            lock(new object()) {
                string fn = string.Format("{0}\\Log\\{1:yyyyMMdd}\\{1:yyyy-MM-dd}-RfidM900.log", Environment.CurrentDirectory, DateTime.Now);
                CreateLogFile(fn);
                using(StreamWriter sw = File.AppendText(fn)) {
                    sw.WriteLine($"{DateTime.Now:HH:mm:ss.fff}  {message}");
                    sw.Close();
                }
            }
        }

        /// <summary>
        ///     写报文记录
        /// </summary>
        /// <param name="emno">表位号，从1开始</param>
        /// <param name="message">报文记录</param>
        public static void WriteLogSendEMByte(int emno, string message) {
            lock(new object()) {
                string fn = string.Format("{0}\\Log\\{1:yyyyMMdd}\\{1:yyyy-MM-dd}-M{2:d2}EM.log", Environment.CurrentDirectory, DateTime.Now, emno + 1);
                if(emno < 0) {
                    fn = string.Format("{0}\\Log\\{1:yyyyMMdd}\\{1:yyyy-MM-dd}-EM.log", Environment.CurrentDirectory, DateTime.Now);
                }
                CreateLogFile(fn);
                //var fileinfo = new FileInfo(fn);
                //当log文件超过2M大小时候，重新分配新的LOG文件
                //if(fileinfo.Length > MaxSize) {
                //    string destFileName = string.Format("{0}\\Log\\{1:yyyyMMdd}\\{1:yyyyMMddHHmmss}-M{2:d2}EM.log", Environment.CurrentDirectory, DateTime.Now, emno);
                //    File.Move(fn, destFileName);
                //    CreateLogFile(fn);
                //}
                using(StreamWriter sw = File.AppendText(fn)) {
                    sw.WriteLine(message);
                    sw.Close();
                }
            }
        }

        /// <summary>
        ///     清除日记文件，只保留最近360天的日记文本
        /// </summary>
        public static void ClearLog(int maxCount = 360) {
            try {
                int maxLogCount = maxCount;
                DirectoryInfo dellogpath = new DirectoryInfo(Environment.CurrentDirectory + "\\Log");
                FileSystemInfo[] files = dellogpath.GetFileSystemInfos();
                int count = files.Length;
                if(count > maxLogCount && maxCount > 0)
                    for(int i = 0; i < count - maxLogCount; i++)
                        Directory.Delete(files[i].FullName, true);
                if(!Directory.Exists(dellogpath.ToString())) Directory.CreateDirectory(dellogpath.ToString());
                string logopath = string.Format("{0}\\Log\\{1:yyyyMMdd}", Environment.CurrentDirectory, DateTime.Now);
                dellogpath = new DirectoryInfo(logopath);
                if(!Directory.Exists(dellogpath.ToString())) Directory.CreateDirectory(dellogpath.ToString());
            }
            catch(Exception ex) {
                WriteLog("ClearLog", ex);
            }
        }

    }
}